//
//  WPPhotoPreviewController.m
//  wobingwoyi
//
//  Created by WGP on 16/8/20.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPPhotoPreviewController.h"
#import "TZPhotoPreviewCell.h"
#import "UIView+Layout.h"
#import "TZImagePickerController.h"
#import "TZImageManager.h"
#import "WPPhotoPreviewCell.h"

@interface WPPhotoPreviewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate> {
    UICollectionView *_collectionView;
    BOOL _isHideNaviBar;
    NSArray *_photosTemp;
    NSArray *_assetsTemp;
    
    UIView *_naviBar;
    UIButton *_backButton;
    
    UIView *_toolBar;
    UIImageView *_numberImageView;
    UILabel *_numberLable;
    UILabel *_titleLabel;
    
    CGFloat _minimumLineSpacing;
}
@end

@implementation WPPhotoPreviewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _minimumLineSpacing = 20;
    [self configCollectionView];
    [self configCustomNaviBar];
}

- (void)setPhotos:(NSMutableArray *)photos {
    _photos = photos;
    _photosTemp = [NSArray arrayWithArray:photos];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
//    if (iOS7Later) [UIApplication sharedApplication].statusBarHidden = YES;
    if (_currentIndex) [_collectionView setContentOffset:CGPointMake((self.view.tz_width + _minimumLineSpacing) * _currentIndex, 0) animated:NO];
    [self refreshNaviBarAndBottomBarState];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    if (iOS7Later) [UIApplication sharedApplication].statusBarHidden = NO;
}

- (void)configCustomNaviBar {
    _naviBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.tz_width, 64)];
    _naviBar.backgroundColor = [UIColor colorWithRed:(34/255.0) green:(34/255.0)  blue:(34/255.0) alpha:1.0];
    _naviBar.alpha = 0.7;
    
    _backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 44, 44)];
    [_backButton setImage:[UIImage imageNamedFromMyBundle:@"navi_back.png"] forState:UIControlStateNormal];
    [_backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.text = [NSString stringWithFormat:@"%zd / %zd",self.currentIndex+1,self.photos.count];
    _titleLabel.font = [UIFont systemFontOfSize:18];
    _titleLabel.textColor = [UIColor whiteColor];
    [_titleLabel sizeToFit];
    _titleLabel.center = _naviBar.center;
    
    [_naviBar addSubview:_titleLabel];
    [_naviBar addSubview:_backButton];
    [self.view addSubview:_naviBar];
}

- (void)configCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(self.view.tz_width, self.view.tz_height);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = _minimumLineSpacing;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.tz_width , self.view.tz_height) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor blackColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.scrollsToTop = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.contentOffset = CGPointMake(0, 0);
    _collectionView.contentSize = CGSizeMake(self.view.tz_width * _photos.count, self.view.tz_height);
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[WPPhotoPreviewCell class] forCellWithReuseIdentifier:@"WPPhotoPreviewCell"];
}

#pragma mark - Click Event

- (void)back
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint offSet = scrollView.contentOffset;
    CGFloat offSetWidth = offSet.x;
    if ((offSetWidth + ((self.view.tz_width + _minimumLineSpacing) * 0.5)) < scrollView.contentSize.width + _minimumLineSpacing) {
        offSetWidth = offSetWidth +  ((self.view.tz_width + _minimumLineSpacing) * 0.5);
    }
    
    NSInteger currentIndex = offSetWidth / (self.view.tz_width + _minimumLineSpacing);
    
    
    if (_currentIndex != currentIndex) {
        
        _titleLabel.text = [NSString stringWithFormat:@"%zd / %zd",currentIndex+1,self.photos.count];
        [_titleLabel sizeToFit];
        
        _currentIndex = currentIndex;
        [self refreshNaviBarAndBottomBarState];
    }
}

#pragma mark - UICollectionViewDataSource && Delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.photos.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TZPhotoPreviewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WPPhotoPreviewCell" forIndexPath:indexPath];
    cell.model = _photos[indexPath.row];
    
    __block BOOL _weakIsHideNaviBar = _isHideNaviBar;
    __weak typeof(_naviBar) weakNaviBar = _naviBar;
    __weak typeof(_toolBar) weakToolBar = _toolBar;
    if (!cell.singleTapGestureBlock) {
        cell.singleTapGestureBlock = ^(){
            // show or hide naviBar / 显示或隐藏导航栏
            _weakIsHideNaviBar = !_weakIsHideNaviBar;
            weakNaviBar.hidden = _weakIsHideNaviBar;
            weakToolBar.hidden = _weakIsHideNaviBar;
        };
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell isKindOfClass:[TZPhotoPreviewCell class]]) {
        [(TZPhotoPreviewCell *)cell recoverSubviews];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell isKindOfClass:[TZPhotoPreviewCell class]]) {
        [(TZPhotoPreviewCell *)cell recoverSubviews];
    }
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    CGFloat contentOffsetX = scrollView.contentOffset.x;
    NSInteger MAX_INDEX = (scrollView.contentSize.width + _minimumLineSpacing)/(self.view.tz_width + _minimumLineSpacing) - 1;
    NSInteger MIN_INDEX = 0;
    
    NSInteger index = contentOffsetX/(self.view.tz_width + _minimumLineSpacing);
    
    if (velocity.x > 0.4 && contentOffsetX < (*targetContentOffset).x) {
        index = index + 1;
    }
    else if (velocity.x < -0.4 && contentOffsetX > (*targetContentOffset).x) {
        index = index;
    }
    else if (contentOffsetX > (index + 0.5) * (self.view.tz_width + _minimumLineSpacing)) {
        index = index + 1;
    }
    
    if (index > MAX_INDEX) index = MAX_INDEX;
    if (index < MIN_INDEX) index = MIN_INDEX;
    
    CGPoint newTargetContentOffset= CGPointMake(index * (self.view.tz_width + _minimumLineSpacing), 0);
    *targetContentOffset = CGPointMake(scrollView.contentOffset.x, 0);
    [scrollView setContentOffset:newTargetContentOffset animated:YES];
}

#pragma mark - Private Method

- (void)refreshNaviBarAndBottomBarState {

    
    _numberLable.text = [NSString stringWithFormat:@"%zd",_photos.count];
    _numberImageView.hidden = (_photos.count <= 0 || _isHideNaviBar);
    _numberLable.hidden = (_photos.count <= 0 || _isHideNaviBar);
    
}


@end
